package wpwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wpwork.base.service.SuperServiceImpl;
import wpwork.base.vo.PageListVO;
import wpwork.base.vo.PaginationVO;
import wpwork.entity.GpsInfoEntity;
import wpwork.entity.WorkPersonJobEntity;
import wpwork.entity.WorkRsinspectionEntity;
import wpwork.mapper.WorkPersonJobMapper;
import wpwork.mapper.WorkRsinspectionMapper;
import wpwork.model.TaskInfoVO;
import wpwork.model.WorkPersonJobDTO;
import wpwork.model.WorkPersonJobQueryVO;
import wpwork.model.WorkPersonJobVO;
import wpwork.permission.entity.UserEntity;
import wpwork.permission.mapper.UserMapper;
import wpwork.service.WorkPersonJobService;
import wpwork.service.WorkRsinspectionService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 *
 * @author wpwork开发平台组
 * @version V3.1.0
 * @copyright 武汉维普科技有限公司
 * @date 2021/3/16 9:47
 */
@Service
@Slf4j
public class WorkPersonJobServiceImpl extends SuperServiceImpl<WorkPersonJobMapper, WorkPersonJobEntity> implements WorkPersonJobService {

    @Autowired
    private WorkPersonJobMapper workPersonJobMapper;
    @Autowired
    private UserMapper userMapper;

    public void generatePersonJobFromAttendance(){
        workPersonJobMapper.generatePersonJobFromAttendance();
    }

    @Override
    public List<WorkPersonJobVO> attendanceStatistics(String startTime, String endTime) {
        List<WorkPersonJobVO> workPersonJobVOS = new ArrayList<>();
            if("".equals(startTime) && "".equals(endTime)){
                workPersonJobVOS = workPersonJobMapper.attendanceStatistics();
            }else if (!"".equals(startTime) && "".equals(endTime)){
                workPersonJobVOS = workPersonJobMapper.attendanceStatisticsStartTime(startTime);
            } else if ( "".equals(startTime) && !"".equals(endTime)) {
                workPersonJobVOS = workPersonJobMapper.attendanceStatisticsEndTime(endTime);
            } else if ( !"".equals(startTime) && !"".equals(endTime)) {
                workPersonJobVOS = workPersonJobMapper.attendanceStatisticsStartTimeAndEndTime(startTime,endTime);
            }
        return workPersonJobVOS;
    }


    @Override
    public List<WorkPersonJobVO> homeStatistics(String type,String startTime, String endTime, String name) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate;
        Date endDate;
        LambdaQueryWrapper<WorkPersonJobEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkPersonJobEntity::getType, type);
        if (!"".equals(startTime) && "".equals(endTime)){
            try {
                startDate = sdf.parse(startTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.ge(WorkPersonJobEntity::getBegindate, startDate)
                            .or()
                            .ge(WorkPersonJobEntity::getEnddate, startDate)
            );
        } else if ( "".equals(startTime) && !"".equals(endTime)) {
            try {
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.le(WorkPersonJobEntity::getBegindate, endDate)
                            .or()
                            .le(WorkPersonJobEntity::getEnddate, endDate)
            );
        } else if ( !"".equals(startTime) && !"".equals(endTime)) {
            try {
                startDate = sdf.parse(startTime);
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.ge(WorkPersonJobEntity::getBegindate, startDate)
                            .or().ge(WorkPersonJobEntity::getEnddate, startDate)
            ).and(wrapper ->
                    wrapper.le(WorkPersonJobEntity::getBegindate, endDate)
                            .or().le(WorkPersonJobEntity::getEnddate, endDate)
            );
        }
        queryWrapper.orderByDesc(WorkPersonJobEntity::getExecutionDate);
        List<WorkPersonJobEntity> workPersonJobEntities = workPersonJobMapper.selectList(queryWrapper);
        List<WorkPersonJobVO> workPersonJobVOS = entityToVO(workPersonJobEntities,name);
        return workPersonJobVOS;
    }

    @Override
    public List<WorkPersonJobVO> homeStatisticsByExecutionDate(String type,String startTime, String endTime, String name) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate;
        Date endDate;
        LambdaQueryWrapper<WorkPersonJobEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkPersonJobEntity::getType, type);
        if ("".equals(startTime) && "".equals(endTime)) {
            LocalDate today = LocalDate.now();
            LocalDateTime startOfDay = today.atStartOfDay();
            LocalDateTime endOfDay = today.atTime(23, 59, 59);
            ZoneId zoneId = ZoneId.systemDefault();
            startDate = Date.from(startOfDay.atZone(zoneId).toInstant());
            endDate = Date.from(endOfDay.atZone(zoneId).toInstant());
            queryWrapper.between(WorkPersonJobEntity::getExecutionDate, startDate, endDate);
        }else if (!"".equals(startTime) && "".equals(endTime)){
            try {
                startDate = sdf.parse(startTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.ge(WorkPersonJobEntity::getExecutionDate, startDate)
            );
        } else if ( "".equals(startTime) && !"".equals(endTime)) {
            try {
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.le(WorkPersonJobEntity::getExecutionDate, endDate)
            );
        } else if ( !"".equals(startTime) && !"".equals(endTime)) {
            try {
                startDate = sdf.parse(startTime);
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.ge(WorkPersonJobEntity::getExecutionDate, startDate)
            ).and(wrapper ->
                    wrapper.le(WorkPersonJobEntity::getExecutionDate, endDate)
            );
        }
        List<WorkPersonJobEntity> workPersonJobEntities = workPersonJobMapper.selectList(queryWrapper);
        List<WorkPersonJobVO> workPersonJobVOS = entityToVO(workPersonJobEntities,name);
        return workPersonJobVOS;
    }

    public List<WorkPersonJobVO> entityToVO(List<WorkPersonJobEntity> workPersonJobEntities, String name) {
        List<WorkPersonJobVO> workPersonJobVOS = new ArrayList<>();
        for (WorkPersonJobEntity workPersonJobEntity : workPersonJobEntities) {
            WorkPersonJobVO workPersonJobVO = new WorkPersonJobVO();
            UserEntity userEntity = userMapper.selectById(workPersonJobEntity.getJobUserId());
            if(name!=null || "".equals(name)){
                if(!userEntity.getRealName().contains(name)){
                    continue;
                }
            }
            workPersonJobVO.setRealName(userEntity.getRealName());
            workPersonJobVO.setId(workPersonJobEntity.getId());
            workPersonJobVO.setType(workPersonJobEntity.getType());
            workPersonJobVO.setResourcesId(workPersonJobEntity.getResourcesId());
            workPersonJobVO.setJobUserId(workPersonJobEntity.getJobUserId());
            workPersonJobVO.setImageurl(workPersonJobEntity.getImageurl());
            workPersonJobVO.setVideourl(workPersonJobEntity.getVideourl());
            workPersonJobVO.setJobinfo(workPersonJobEntity.getJobinfo());
            workPersonJobVO.setRemark(workPersonJobEntity.getRemark());
            workPersonJobVO.setEnabledMark(workPersonJobEntity.getEnabledMark());
            workPersonJobVO.setSortCode(workPersonJobEntity.getSortCode());
            workPersonJobVO.setCreatorTime(workPersonJobEntity.getCreatorTime());
            workPersonJobVO.setCreatorUserId(workPersonJobEntity.getCreatorUserId());
            workPersonJobVO.setLastModifyTime(workPersonJobEntity.getLastModifyTime());
            workPersonJobVO.setLastModifyUserId(workPersonJobEntity.getLastModifyUserId());
            workPersonJobVO.setDeleteTime(workPersonJobEntity.getDeleteTime());
            workPersonJobVO.setDeleteUserId(workPersonJobEntity.getDeleteUserId());
            workPersonJobVO.setDeleteMark(workPersonJobEntity.getDeleteMark());
            workPersonJobVO.setTenantId(workPersonJobEntity.getTenantId());
            workPersonJobVO.setExecutionDate(workPersonJobEntity.getExecutionDate());
            workPersonJobVO.setLocation(workPersonJobEntity.getLocation());
            workPersonJobVO.setBegindate(workPersonJobEntity.getBegindate());
            workPersonJobVO.setEnddate(workPersonJobEntity.getEnddate());
            workPersonJobVO.setText(workPersonJobEntity.getText());
            workPersonJobVO.setExecutionStatus(workPersonJobEntity.getExecutionStatus());
            workPersonJobVO.setInstantperson(workPersonJobEntity.getInstantperson());
            workPersonJobVO.setExecutionTime(workPersonJobEntity.getExecutionTime());
            workPersonJobVO.setExecutionLocation(workPersonJobEntity.getExecutionLocation());
            workPersonJobVO.setLocationDesc(workPersonJobEntity.getLocationDesc());
            workPersonJobVO.setTaskNumber(workPersonJobEntity.getTaskNumber());
            workPersonJobVOS.add(workPersonJobVO);
        }
        return workPersonJobVOS;
    }

    @Override
    public List<TaskInfoVO> getInfoByTaskNum(String taskNum){
        return workPersonJobMapper.getInfoByTaskNum(taskNum);
    }


    @Override
    public List<WorkPersonJobEntity> getInfoListByTaskNum(String taskNum){
        return workPersonJobMapper.getInfoListByTaskNum(taskNum);
    }

    @Override
    public PageListVO<WorkPersonJobDTO> getWorkPersonJobPage(WorkPersonJobQueryVO queryVO) {

        // 日期格式处理
        if (queryVO.getStartDate() != null) {
            log.info("startDate类型: {}, 值: {}", queryVO.getStartDate().getClass().getName(), queryVO.getStartDate());
        }
        if (queryVO.getEndDate() != null) {
            log.info("endDate类型: {}, 值: {}", queryVO.getEndDate().getClass().getName(), queryVO.getEndDate());
        }

        log.info("PSQL查询参数 - fType: {}, fText: {}, fExecutionStatus: {}, fRealName: {}, fAccount: {}, fTaskNumber: {}, startDate: {}, endDate: {}, page: {}, size: {}",
                queryVO.getFType(), queryVO.getFText(), queryVO.getFExecutionStatus(),
                queryVO.getFRealName(), queryVO.getFAccount(), queryVO.getFTaskNumber(),
                queryVO.getStartDate(), queryVO.getEndDate(), queryVO.getPage(), queryVO.getSize());

        // 计算分页偏移量
        Long offset = (long) (queryVO.getPage() - 1) * queryVO.getSize();

        // 查询数据
        List<WorkPersonJobDTO> list = workPersonJobMapper.selectWorkPersonJobPage(
                queryVO, offset, queryVO.getSize());

        // 查询总数
        Long total = workPersonJobMapper.selectWorkPersonJobCount(queryVO);

        log.info("PSQL查询结果 - 总数: {}, 当前页数据量: {}", total, list.size());

        // 构建分页信息
        PaginationVO pagination = new PaginationVO();
        pagination.setCurrentPage(Long.valueOf(queryVO.getPage()));
        pagination.setPageSize(Long.valueOf(queryVO.getSize()));
        pagination.setTotal(total.intValue());

        // 返回分页结果
        PageListVO<WorkPersonJobDTO> result = new PageListVO<>();
        result.setList(list);
        result.setPagination(pagination);

        return result;
    }

}
